<template>
  <div class="admin-dashboard">
    <!-- 侧边栏 -->
    <aside class="sidebar">
      <div class="sidebar-header">
        <div class="logo">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M2 17L12 22L22 17" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M2 12L12 17L22 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          <span>管理端</span>
        </div>
      </div>
      
      <nav class="sidebar-nav">
        <ul class="nav-list">
          <li class="nav-item" :class="{ active: currentPage === 'analytics' }">
            <button @click="handlePageChange('analytics')" class="nav-link">
              <svg class="nav-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <line x1="18" y1="20" x2="18" y2="10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <line x1="12" y1="20" x2="12" y2="4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <line x1="6" y1="20" x2="6" y2="14" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
              数据分析
            </button>
          </li>
          <li class="nav-item" :class="{ active: currentPage === 'file-upload' }">
            <button @click="handlePageChange('file-upload')" class="nav-link">
              <svg class="nav-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <polyline points="7,10 12,15 17,10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <line x1="12" y1="15" x2="12" y2="3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
              文件上传
            </button>
          </li>
          <li class="nav-item" :class="{ active: currentPage === 'users' }">
            <button @click="handlePageChange('users')" class="nav-link">
              <svg class="nav-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <circle cx="9" cy="7" r="4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M23 21v-2a4 4 0 0 0-3-3.87" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M16 3.13a4 4 0 0 1 0 7.75" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
              用户管理
            </button>
          </li>
          <li class="nav-item" :class="{ active: currentPage === 'chat-history' }">
            <button @click="handlePageChange('chat-history')" class="nav-link">
              <svg class="nav-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
              对话历史
            </button>
          </li>
        </ul>
      </nav>
      
      <div class="sidebar-footer">
        <button @click="logout" class="logout-btn">
          <svg class="logout-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <polyline points="16,17 21,12 16,7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <line x1="21" y1="12" x2="9" y2="12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          退出登录
        </button>
      </div>
    </aside>
    
    <!-- 主内容区域 -->
    <main class="main-content">
      <!-- 顶部导航栏 -->
      <header class="top-header">
        <div class="header-left">
          <h1 class="page-title">{{ getPageTitle() }}</h1>
        </div>
        <div class="header-right">
          <div class="admin-info">
            <span class="admin-name">管理员</span>
            <div class="admin-avatar">A</div>
          </div>
        </div>
      </header>
      
      <!-- 页面内容 -->
      <div class="page-content">
        <!-- 文件上传页面 -->
        <div v-if="currentPage === 'file-upload'" class="file-upload-page">
          <div class="page-header">
            <!-- <h2>添加日志文件</h2> -->
            <p>上传日志文件以扩充系统知识库</p>
          </div>
          
          <div class="upload-section">
            <AdminLogFileUpload @upload-success="handleUploadSuccess" @upload-error="handleUploadError" />
          </div>
          
        </div>
        
        <!-- 用户管理页面 -->
        <div v-if="currentPage === 'users'" class="users-page">
          <div class="page-header">
            <p>查看和管理系统用户</p>
          </div>
          
          <!-- 用户统计 -->
          <div class="user-stats">
            <div class="stat-item">
              <span class="stat-label">总用户数:</span>
              <span class="stat-value">{{ userStats.total }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">活跃用户:</span>
              <span class="stat-value">{{ userStats.active }}</span>
            </div>
            <!-- <div class="stat-item">
              <span class="stat-label">禁用用户:</span>
              <span class="stat-value">{{ userStats.inactive }}</span>
            </div> -->
          </div>
          
          <!-- 用户列表 -->
          <div class="users-table">
            <div class="table-header">
              <div class="table-cell">用户名</div>
              <div class="table-cell">邮箱</div>
              <div class="table-cell">注册时间</div>
              <div class="table-cell">最后登录</div>
              <div class="table-cell">状态</div>
              <div class="table-cell">操作</div>
            </div>
            
            <div v-if="loadingUsers" class="loading-state">
              <div class="loading-spinner"></div>
              <span>加载中...</span>
            </div>
            
            <div v-else-if="users.length === 0" class="empty-state">
              <p>暂无用户数据</p>
            </div>
            
            <div v-else class="table-body">
              <div v-for="user in users" :key="user.id" class="table-row">
                <div class="table-cell">{{ user.username }}</div>
                <div class="table-cell">{{ user.email || '未设置' }}</div>
                <div class="table-cell">{{ user.created_at }}</div>
                <div class="table-cell">{{ user.last_login || '从未登录' }}</div>
                <div class="table-cell">
                  <span class="status-badge" :class="{ active: user.is_active, inactive: !user.is_active }">
                    {{ user.is_active ? '活跃' : '禁用' }}
                  </span>
                </div>
                <div class="table-cell">
                  <button class="edit-btn" @click="editUser(user)">编辑</button>
                  <button v-if="user.username !== 'admin'" class="delete-btn" @click="deleteUser(user)">删除</button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 分页 -->
          <div v-if="userPagination.total > userPagination.pageSize" class="pagination">
            <button 
              class="page-btn" 
              :disabled="userPagination.page <= 1"
              @click="loadUsers(userPagination.page - 1)"
            >
              上一页
            </button>
            <span class="page-info">
              第 {{ userPagination.page }} 页，共 {{ Math.ceil(userPagination.total / userPagination.pageSize) }} 页
            </span>
            <button 
              class="page-btn" 
              :disabled="userPagination.page >= Math.ceil(userPagination.total / userPagination.pageSize)"
              @click="loadUsers(userPagination.page + 1)"
            >
              下一页
            </button>
          </div>
        </div>
        
        <!-- 对话历史页面 -->
        <div v-if="currentPage === 'chat-history'" class="chat-history-page">
          <div class="page-header">
            <!-- <h2>对话历史</h2> -->
            <p>查看用户对话记录</p>
          </div>
          
          <div class="history-filters">
            <div class="filter-group">
              <label>用户名搜索：</label>
              <input 
                type="text" 
                v-model="chatHistoryFilters.username" 
                class="filter-input" 
                placeholder="留空查询所有用户"
                @keyup.enter="applyChatHistoryFilters"
              />
            </div>
            
            <div class="filter-group">
              <button @click="applyChatHistoryFilters" class="filter-apply-btn">
                <svg class="filter-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <circle cx="11" cy="11" r="8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  <path d="m21 21-4.35-4.35" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                搜索
              </button>
              <button @click="resetChatHistoryFilters" class="filter-reset-btn">
                <svg class="filter-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M1 4v6h6M23 20v-6h-6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  <path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                重置
              </button>
            </div>
          </div>
          
          <!-- 当前筛选状态提示 -->
          <div v-if="!loadingChatHistory && chatHistory.length > 0" class="filter-status">
            <div class="status-item">
              <svg class="status-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M12 6v6l4 2" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
              <span v-if="!chatHistoryFilters.username">
                显示所有用户的对话记录
              </span>
              <span v-else>
                用户: <strong>{{ chatHistoryFilters.username }}</strong>
              </span>
            </div>
          </div>
          
          <div v-if="loadingChatHistory" class="loading-state">
            <div class="loading-spinner"></div>
            <span>加载对话历史中...</span>
          </div>
          
          <div v-else-if="chatHistory.length === 0" class="empty-state">
            <div class="empty-icon">💬</div>
            <p>暂无对话历史</p>
          </div>
          
          <div v-else class="chat-history-list">
            <div 
              v-for="(conversation, index) in groupedChatHistory" 
              :key="conversation.session_id" 
              class="history-item"
              :class="{ expanded: expandedSessions.has(conversation.session_id) }"
              @click="toggleSessionExpand(conversation.session_id)"
            >
              <div class="history-header">
                <div class="user-info">
                  <span class="username">{{ conversation.username }}</span>
                  <span class="session-id">{{ conversation.session_id }}</span>
                  <span class="message-count">{{ conversation.messages.length }} 条消息</span>
                </div>
                <div class="header-actions">
                  <span class="timestamp">{{ conversation.timestamp }}</span>
                  <span class="expand-icon">
                    {{ expandedSessions.has(conversation.session_id) ? '▼' : '▶' }}
                  </span>
                </div>
              </div>
              
              <!-- 折叠状态：显示预览 -->
              <div v-if="!expandedSessions.has(conversation.session_id)" class="history-preview">
                <div class="preview-text">{{ conversation.preview }}</div>
                <div class="preview-hint">点击查看完整对话</div>
              </div>
              
              <!-- 展开状态：显示完整对话 -->
              <div v-else class="history-details" @click.stop>
                <div 
                  v-for="(message, msgIndex) in conversation.messages" 
                  :key="msgIndex" 
                  class="message-item"
                  :class="message.type"
                >
                  <div class="message-label">{{ message.type === 'user' ? '用户' : 'AI' }}</div>
                  <div 
                    v-if="message.type === 'user'" 
                    class="message-content"
                  >{{ message.content }}</div>
                  <div 
                    v-else 
                    class="message-content markdown-content"
                    v-html="renderMarkdown(message.content)"
                  ></div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 分页 -->
          <div v-if="chatHistoryPagination.total > chatHistoryPagination.pageSize" class="pagination">
            <button 
              class="page-btn" 
              :disabled="chatHistoryPagination.page <= 1"
              @click="loadChatHistory(chatHistoryPagination.page - 1)"
            >
              上一页
            </button>
            <span class="page-info">
              第 {{ chatHistoryPagination.page }} 页，共 {{ Math.ceil(chatHistoryPagination.total / chatHistoryPagination.pageSize) }} 页
              (总计 {{ chatHistoryPagination.total }} 条记录)
            </span>
            <button 
              class="page-btn" 
              :disabled="chatHistoryPagination.page >= Math.ceil(chatHistoryPagination.total / chatHistoryPagination.pageSize)"
              @click="loadChatHistory(chatHistoryPagination.page + 1)"
            >
              下一页
            </button>
          </div>
        </div>
        
        <!-- 数据分析页面 -->
        <div v-if="currentPage === 'analytics'" class="analytics-page">
          <div class="page-header">
            <!-- <h2>数据分析</h2> -->
            <p>系统使用情况统计和分析</p>
          </div>
          
          <!-- 加载状态 -->
          <div v-if="loadingAnalytics" class="loading-state">
            <div class="loading-spinner"></div>
            <span>加载数据分析中...</span>
          </div>
          
          <div v-else>
            <!-- 统计卡片 -->
            <div class="stats-overview">
              <div class="stat-box">
                <div class="stat-icon users-stat">
                  <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" stroke="currentColor" stroke-width="2"/>
                    <circle cx="9" cy="7" r="4" stroke="currentColor" stroke-width="2"/>
                  </svg>
                </div>
                <div class="stat-details">
                  <div class="stat-value">{{ analyticsData.total_users || 0 }}</div>
                  <div class="stat-label">总用户数</div>
                </div>
              </div>
              
              <div class="stat-box">
                <div class="stat-icon conversations-stat">
                  <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" stroke="currentColor" stroke-width="2"/>
                  </svg>
                </div>
                <div class="stat-details">
                  <div class="stat-value">{{ analyticsData.total_conversations || 0 }}</div>
                  <div class="stat-label">总对话数</div>
                </div>
              </div>
              
              <div class="stat-box">
                <div class="stat-icon active-stat">
                  <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                    <path d="M12 6v6l4 2" stroke="currentColor" stroke-width="2"/>
                  </svg>
                </div>
                <div class="stat-details">
                  <div class="stat-value">{{ analyticsData.active_users || 0 }}</div>
                  <div class="stat-label">活跃用户（7天）</div>
                </div>
              </div>
              
              <div class="stat-box">
                <div class="stat-icon messages-stat">
                  <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" stroke="currentColor" stroke-width="2"/>
                  </svg>
                </div>
                <div class="stat-details">
                  <div class="stat-value">{{ analyticsData.total_messages || 0 }}</div>
                  <div class="stat-label">总消息数</div>
                </div>
              </div>
            </div>
            
            <!-- 活跃用户排行 -->
            <div class="ranking-section">
              <h3>
                <svg class="chart-title-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26L12 2Z" stroke="currentColor" stroke-width="2"/>
                </svg>
                活跃用户排行 Top 10
              </h3>
              <div class="ranking-list">
                <div 
                  v-for="(user, index) in analyticsData.top_users" 
                  :key="index"
                  class="ranking-item"
                  :class="{ 'top-three': index < 3 }"
                >
                  <div class="rank-badge" :class="`rank-${index + 1}`">
                    {{ index + 1 }}
                  </div>
                  <div class="rank-user">
                    <span class="user-avatar">{{ user.username?.[0]?.toUpperCase() }}</span>
                    <span class="user-name">{{ user.username }}</span>
                  </div>
                  <div class="rank-count">
                    <span class="count-number">{{ user.conversation_count }}</span>
                    <span class="count-label">次对话</span>
                  </div>
                  <div class="rank-bar">
                    <div 
                      class="rank-bar-fill"
                      :style="{ width: getRankBarWidth(user.conversation_count, analyticsData.top_users[0]?.conversation_count) }"
                    ></div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 平均统计 -->
            <!-- <div class="avg-stats">
              <div class="avg-stat-item">
                <div class="avg-icon">
                  <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                    <path d="M9 9h6v6H9z" stroke="currentColor" stroke-width="2"/>
                  </svg>
                </div>
                <div class="avg-content">
                  <div class="avg-value">{{ analyticsData.avg_messages_per_session || 0 }}</div>
                  <div class="avg-label">平均每次对话消息数</div>
                </div>
              </div>
            </div> -->
            
            <!-- 新增图表区域 -->
            <div class="advanced-charts">
              <!-- 24小时活跃度折线图 -->
              <div class="chart-card line-chart-card full-width">
                <h3>
                  <svg class="chart-title-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M12 2v20M2 12h20" stroke="currentColor" stroke-width="2"/>
                    <path d="M6 8l6 6 6-6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                  </svg>
                  24小时活跃度分布
                </h3>
                <div class="line-chart-container">
                  <svg class="line-chart-svg" viewBox="0 0 800 300" preserveAspectRatio="xMidYMid meet">
                    <!-- 网格线 -->
                    <line v-for="i in 5" :key="'h-grid-' + i" 
                          :x1="60" :y1="i * 50" 
                          :x2="780" :y2="i * 50" 
                          stroke="rgba(148, 163, 184, 0.1)" stroke-width="1"/>
                    
                    <!-- 数据折线 -->
                    <polyline 
                      :points="getLineChartPoints(analyticsData.hourly_activity)"
                      fill="none"
                      stroke="url(#lineGradient)"
                      stroke-width="3"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                    />
                    
                    <!-- 填充区域 -->
                    <polygon 
                      :points="getLineChartArea(analyticsData.hourly_activity)"
                      fill="url(#areaGradient)"
                      opacity="0.3"
                    />
                    
                    <!-- 数据点 -->
                    <circle 
                      v-for="(point, idx) in getLineChartDataPoints(analyticsData.hourly_activity)"
                      :key="'point-' + idx"
                      :cx="point.x"
                      :cy="point.y"
                      r="5"
                      fill="#3b82f6"
                      stroke="#fff"
                      stroke-width="2"
                      class="data-point"
                    >
                      <title>{{ point.label }}: {{ point.value }}次</title>
                    </circle>
                    
                    <!-- X轴标签 -->
                    <text v-for="(item, idx) in analyticsData.hourly_activity.filter((_, i) => i % 4 === 0)"
                          :key="'x-label-' + idx"
                          :x="60 + (analyticsData.hourly_activity.indexOf(item) * (720 / Math.max(1, analyticsData.hourly_activity.length - 1)))"
                          y="280"
                          text-anchor="middle"
                          fill="#94a3b8"
                          font-size="12">
                      {{ item.hour }}
                    </text>
                    
                    <!-- 渐变定义 -->
                    <defs>
                      <linearGradient id="lineGradient" x1="0%" y1="0%" x2="100%" y2="0%">
                        <stop offset="0%" stop-color="#3b82f6"/>
                        <stop offset="100%" stop-color="#8b5cf6"/>
                      </linearGradient>
                      <linearGradient id="areaGradient" x1="0%" y1="0%" x2="0%" y2="100%">
                        <stop offset="0%" stop-color="#3b82f6" stop-opacity="0.5"/>
                        <stop offset="100%" stop-color="#3b82f6" stop-opacity="0"/>
                      </linearGradient>
                    </defs>
                  </svg>
                </div>
              </div>
              
              <!-- 故障类型分布饼图 -->
              <div class="chart-card pie-chart-card full-width">
                <h3>
                  <svg class="chart-title-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                    <path d="M12 2a10 10 0 0 1 10 10h-10V2z" fill="currentColor" opacity="0.3"/>
                  </svg>
                  故障类型分布
                </h3>
                <div class="pie-chart-container">
                  <div class="pie-chart-wrapper">
                    <svg class="pie-chart-svg" viewBox="0 0 400 400">
                      <g v-for="(slice, idx) in getPieSlices(analyticsData.fault_distribution)" 
                         :key="'slice-' + idx"
                         class="pie-slice">
                        <path 
                          :d="slice.path"
                          :fill="slice.color"
                          :stroke="'#1e293b'"
                          stroke-width="2"
                          class="pie-path"
                          @mouseenter="hoveredSlice = idx"
                          @mouseleave="hoveredSlice = null"
                          :style="{ transform: hoveredSlice === idx ? 'scale(1.05)' : 'scale(1)', transformOrigin: '200px 200px' }"
                        >
                          <title>{{ slice.label }}: {{ slice.value }}次 ({{ slice.percentage }}%)</title>
                        </path>
                      </g>
                    </svg>
                  </div>
                  
                  <!-- 图例 -->
                  <div class="pie-legend">
                    <div v-for="(item, idx) in analyticsData.fault_distribution" 
                         :key="'legend-' + idx"
                         class="legend-item"
                         @mouseenter="hoveredSlice = idx"
                         @mouseleave="hoveredSlice = null">
                      <span class="legend-color" :style="{ background: getPieColor(idx) }"></span>
                      <span class="legend-label">{{ item.type }}</span>
                      <span class="legend-value">{{ item.count }}次</span>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 问题解决率趋势折线图 -->
              <div class="chart-card resolution-chart-card full-width">
                <h3>
                  <svg class="chart-title-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" stroke="currentColor" stroke-width="2"/>
                    <polyline points="22 4 12 14.01 9 11.01" stroke="currentColor" stroke-width="2"/>
                  </svg>
                  问题解决率趋势（近7天）
                </h3>
                <div class="resolution-chart-container">
                  <svg class="resolution-chart-svg" viewBox="0 0 600 250" preserveAspectRatio="xMidYMid meet">
                    <!-- 网格线 -->
                    <line v-for="i in 5" :key="'res-grid-' + i" 
                          :x1="60" :y1="i * 40" 
                          :x2="560" :y2="i * 40" 
                          stroke="rgba(148, 163, 184, 0.1)" stroke-width="1"/>
                    
                    <!-- Y轴标签 (0-100%) -->
                    <text v-for="i in 6" :key="'y-label-' + i"
                          x="45" 
                          :y="210 - ((i - 1) * 40)"
                          text-anchor="end"
                          fill="#94a3b8"
                          font-size="11">
                      {{ (i - 1) * 20 }}%
                    </text>
                    
                    <!-- 数据折线 -->
                    <polyline 
                      :points="getResolutionLinePoints(analyticsData.resolution_trend)"
                      fill="none"
                      stroke="#10b981"
                      stroke-width="3"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                    />
                    
                    <!-- 填充区域 -->
                    <polygon 
                      :points="getResolutionArea(analyticsData.resolution_trend)"
                      fill="url(#resolutionGradient)"
                      opacity="0.2"
                    />
                    
                    <!-- 数据点 -->
                    <g v-for="(point, idx) in getResolutionDataPoints(analyticsData.resolution_trend)"
                       :key="'res-point-' + idx">
                      <circle 
                        :cx="point.x"
                        :cy="point.y"
                        r="6"
                        fill="#10b981"
                        stroke="#fff"
                        stroke-width="2"
                      />
                      <text 
                        :x="point.x"
                        :y="point.y - 15"
                        text-anchor="middle"
                        fill="#10b981"
                        font-size="12"
                        font-weight="600">
                        {{ point.value }}%
                      </text>
                    </g>
                    
                    <!-- X轴标签 -->
                    <text v-for="(item, idx) in analyticsData.resolution_trend"
                          :key="'res-x-label-' + idx"
                          :x="60 + (idx * (500 / Math.max(1, analyticsData.resolution_trend.length - 1)))"
                          y="235"
                          text-anchor="middle"
                          fill="#94a3b8"
                          font-size="12">
                      {{ item.date }}
                    </text>
                    
                    <!-- 渐变定义 -->
                    <defs>
                      <linearGradient id="resolutionGradient" x1="0%" y1="0%" x2="0%" y2="100%">
                        <stop offset="0%" stop-color="#10b981" stop-opacity="0.5"/>
                        <stop offset="100%" stop-color="#10b981" stop-opacity="0"/>
                      </linearGradient>
                    </defs>
                  </svg>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { marked } from 'marked';
import hljs from 'highlight.js';
import AdminLogFileUpload from '../components/AdminLogFileUpload.vue';
import api from '../api';

// 配置 marked
marked.setOptions({
  highlight: function(code, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(code, { language: lang }).value;
      } catch (err) {
        console.error('Highlight error:', err);
      }
    }
    return hljs.highlightAuto(code).value;
  },
  breaks: true,
  gfm: true,
  headerIds: false,
  mangle: false
});

const currentPage = ref('analytics');
const router = useRouter();

// 用户管理相关数据
const users = ref([]);
const loadingUsers = ref(false);
const userStats = ref({
  total: 0,
  active: 0,
  inactive: 0
});
const userPagination = ref({
  page: 1,
  pageSize: 20,
  total: 0
});

// 对话历史相关数据
const chatHistory = ref([]);
const loadingChatHistory = ref(false);
const chatHistoryFilters = ref({
  user_id: null,
  username: '',
  start_date: '',
  end_date: '',
  page: 1,
  page_size: 20
});
const chatHistoryPagination = ref({
  page: 1,
  pageSize: 20,
  total: 0
});
const expandedSessions = ref(new Set());

// 数据分析相关数据
const loadingAnalytics = ref(false);
const hoveredSlice = ref(null); // 饼图悬浮状态
const analyticsData = ref({
  total_users: 0,
  total_conversations: 0,
  active_users: 0,
  total_messages: 0,
  user_growth: [],
  conversation_trend: [],
  top_users: [],
  avg_messages_per_session: 0,
  hourly_activity: [],
  fault_distribution: [],
  resolution_trend: []
});

onMounted(() => {
  // 检查管理员登录状态
  const adminToken = localStorage.getItem('adminToken');
  const adminUser = localStorage.getItem('adminUser');
  
  if (!adminToken || !adminUser) {
    router.push('/admin/login');
    return;
  }
  
  try {
    const userInfo = JSON.parse(adminUser);
    if (userInfo.username !== 'admin') {
      router.push('/admin/login');
    }
  } catch (e) {
    router.push('/admin/login');
  }
  
  // 根据当前页面加载数据
  if (currentPage.value === 'users') {
    loadUsers();
  } else if (currentPage.value === 'chat-history') {
    loadChatHistory();
  } else if (currentPage.value === 'analytics') {
    loadAnalyticsData();
  }
});

const getPageTitle = () => {
  const titles = {
    'file-upload': '文件上传',
    'users': '用户管理',
    'chat-history': '对话历史',
    'analytics': '数据分析'
  };
  return titles[currentPage.value] || '管理端';
};

const logout = () => {
  localStorage.removeItem('adminToken');
  localStorage.removeItem('adminUser');
  router.push('/admin/login');
};

const handleUploadSuccess = (result) => {
  console.log('文件上传成功:', result);
  // 这里可以添加成功提示
};

const handleUploadError = (error) => {
  console.log('文件上传失败:', error);
  // 这里可以添加错误提示
};

// ==================== 用户管理功能 ====================

const loadUsers = async (page = 1) => {
  try {
    loadingUsers.value = true;
    const response = await api.getUsers(page, userPagination.value.pageSize);
    
    users.value = response.data.users;
    userPagination.value = {
      page: response.data.page,
      pageSize: response.data.page_size,
      total: response.data.total
    };
    
    // 计算用户统计
    userStats.value = {
      total: response.data.total,
      active: users.value.filter(user => user.is_active).length,
      inactive: users.value.filter(user => !user.is_active).length
    };
    
  } catch (error) {
    console.error('加载用户列表失败:', error);
    // 这里可以添加错误提示
  } finally {
    loadingUsers.value = false;
  }
};

const editUser = (user) => {
  // 简单的编辑功能，可以扩展为弹窗或跳转页面
  const newEmail = prompt('请输入新邮箱:', user.email || '');
  if (newEmail !== null && newEmail !== user.email) {
    updateUser(user.id, { email: newEmail });
  }
};

const updateUser = async (userId, userData) => {
  try {
    const response = await api.updateUser(userId, userData);
    console.log('用户更新成功:', response.data);
    
    // 重新加载用户列表
    loadUsers(userPagination.value.page);
    
    // 这里可以添加成功提示
  } catch (error) {
    console.error('更新用户失败:', error);
    // 这里可以添加错误提示
  }
};

const deleteUser = async (user) => {
  if (confirm(`确定要删除用户 "${user.username}" 吗？此操作不可恢复。`)) {
    try {
      const response = await api.deleteUser(user.id);
      console.log('用户删除成功:', response.data);
      
      // 重新加载用户列表
      loadUsers(userPagination.value.page);
      
      // 这里可以添加成功提示
    } catch (error) {
      console.error('删除用户失败:', error);
      // 这里可以添加错误提示
    }
  }
};

// ==================== 对话历史功能 ====================

// 将对话历史解析为分组的会话
const groupedChatHistory = computed(() => {
  if (!chatHistory.value || chatHistory.value.length === 0) {
    console.log('📊 [对话历史] 无数据');
    return [];
  }
  
  console.log('📊 [对话历史] 原始数据:', chatHistory.value);
  
  // 每条记录就是一个完整的会话
  const result = chatHistory.value.map(item => {
    const messages = [];
    let preview = '';
    
    console.log(`📋 [会话 ${item.session_id}] 原始内容:`, item.content);
    
    // 解析完整的对话内容
    if (item.content) {
      const lines = item.content.split('\n').filter(line => line.trim());
      console.log(`📋 [会话 ${item.session_id}] 分割后的行数:`, lines.length);
      
      lines.forEach((line, index) => {
        console.log(`  行${index + 1}:`, line);
        
        // 移除时间戳前缀 [2025-10-29 13:07:50]
        let cleanedLine = line.replace(/^\[[\d\-:\s]+\]\s*/, '').trim();
        console.log(`  清理后:`, cleanedLine);
        
        if (cleanedLine.includes('用户：')) {
          const content = cleanedLine.replace('用户：', '').trim();
          messages.push({
            type: 'user',
            content: content
          });
          console.log(`  ✅ 识别为用户消息:`, content.substring(0, 50));
          // 如果还没有预览，使用第一条用户消息作为预览
          if (!preview) {
            preview = content.substring(0, 100) + (content.length > 100 ? '...' : '');
          }
        } else if (cleanedLine.includes('回复：')) {
          const content = cleanedLine.replace('回复：', '').trim();
          messages.push({
            type: 'ai',
            content: content
          });
          console.log(`  ✅ 识别为AI回复:`, content.substring(0, 50));
        } else if (cleanedLine) {
          // 如果有内容但不是"用户："或"回复："开头，可能是多行消息的一部分
          if (messages.length > 0) {
            // 追加到最后一条消息
            messages[messages.length - 1].content += '\n' + cleanedLine;
            console.log(`  ➕ 追加到上一条消息`);
          } else {
            console.log(`  ⚠️  未识别的行格式，且无前置消息`);
          }
        }
      });
    }
    
    console.log(`📋 [会话 ${item.session_id}] 解析结果: ${messages.length} 条消息`);
    
    return {
      session_id: item.session_id,
      user_id: item.user_id,
      username: item.username,
      timestamp: item.timestamp,
      messages: messages,
      preview: preview || '暂无预览'
    };
  });
  
  console.log('📊 [对话历史] 最终分组数据:', result);
  return result;
});

// 切换会话展开/折叠状态
const toggleSessionExpand = (sessionId) => {
  if (expandedSessions.value.has(sessionId)) {
    expandedSessions.value.delete(sessionId);
  } else {
    expandedSessions.value.add(sessionId);
  }
  // 触发响应式更新
  expandedSessions.value = new Set(expandedSessions.value);
};

const loadChatHistory = async (page = 1) => {
  try {
    loadingChatHistory.value = true;
    
    // 构建筛选参数，只包含有值的字段
    const filters = {
      page,
      page_size: chatHistoryPagination.value.pageSize
    };
    
    // 只添加非空的筛选条件
    if (chatHistoryFilters.value.username && chatHistoryFilters.value.username.trim()) {
      filters.username = chatHistoryFilters.value.username.trim();
    }
    if (chatHistoryFilters.value.start_date) {
      filters.start_date = chatHistoryFilters.value.start_date;
    }
    if (chatHistoryFilters.value.end_date) {
      filters.end_date = chatHistoryFilters.value.end_date;
    }
    if (chatHistoryFilters.value.user_id) {
      filters.user_id = chatHistoryFilters.value.user_id;
    }
    
    console.log('📊 [对话历史] 查询参数:', filters);
    
    const response = await api.getChatHistory(filters);
    
    chatHistory.value = response.data.conversations;
    chatHistoryPagination.value = {
      page: response.data.page,
      pageSize: response.data.page_size,
      total: response.data.total
    };
    
    console.log(`✅ [对话历史] 加载成功，共 ${response.data.total} 条记录`);
    
  } catch (error) {
    console.error('❌ [对话历史] 加载失败:', error);
    // 这里可以添加错误提示
  } finally {
    loadingChatHistory.value = false;
  }
};

const applyChatHistoryFilters = () => {
  loadChatHistory(1);
};

const resetChatHistoryFilters = () => {
  chatHistoryFilters.value = {
    user_id: null,
    username: '',
    start_date: '',
    end_date: '',
    page: 1,
    page_size: 20
  };
  loadChatHistory(1);
};

// ==================== 数据分析相关函数 ====================

// 加载数据分析数据
const loadAnalyticsData = async () => {
  loadingAnalytics.value = true;
  try {
    const response = await api.getAnalytics();
    analyticsData.value = response.data;
    console.log('数据分析数据加载成功:', analyticsData.value);
  } catch (error) {
    console.error('加载数据分析失败:', error);
    alert('加载数据分析失败: ' + (error.response?.data?.error || error.message));
  } finally {
    loadingAnalytics.value = false;
  }
};

// 计算排行榜进度条宽度
const getRankBarWidth = (count, maxCount) => {
  if (!count || !maxCount || maxCount === 0) return '10%';
  const percentage = (count / maxCount) * 100;
  return Math.max(10, percentage) + '%'; // 最小10%保证可见
};

// ==================== 图表计算函数 ====================

// 折线图：计算点坐标
const getLineChartPoints = (data) => {
  if (!data || data.length === 0) return '60,250 780,250';
  
  const maxValue = Math.max(...data.map(d => d.count || 0), 1);
  const points = data.map((item, index) => {
    const x = 60 + (index * (720 / Math.max(1, data.length - 1)));
    const y = 250 - ((item.count || 0) / maxValue) * 200;
    return `${x},${y}`;
  });
  
  return points.join(' ');
};

// 折线图：计算填充区域
const getLineChartArea = (data) => {
  if (!data || data.length === 0) return '60,250 780,250';
  
  const points = getLineChartPoints(data);
  const lastX = 60 + ((data.length - 1) * (720 / Math.max(1, data.length - 1)));
  return `60,250 ${points} ${lastX},250`;
};

// 折线图：获取数据点信息
const getLineChartDataPoints = (data) => {
  if (!data || data.length === 0) return [];
  
  const maxValue = Math.max(...data.map(d => d.count || 0), 1);
  return data.map((item, index) => ({
    x: 60 + (index * (720 / Math.max(1, data.length - 1))),
    y: 250 - ((item.count || 0) / maxValue) * 200,
    value: item.count || 0,
    label: item.hour
  }));
};

// 饼图颜色方案
const getPieColor = (index) => {
  const colors = [
    '#3b82f6', // 蓝色
    '#10b981', // 绿色
    '#f59e0b', // 橙色
    '#8b5cf6', // 紫色
    '#ef4444', // 红色
    '#06b6d4', // 青色
  ];
  return colors[index % colors.length];
};

// 饼图：计算扇形路径
const getPieSlices = (data) => {
  if (!data || data.length === 0) return [];
  
  const total = data.reduce((sum, item) => sum + (item.count || 0), 0);
  if (total === 0) return [];
  
  let currentAngle = -90; // 从顶部开始
  const radius = 120;
  const cx = 200;
  const cy = 200;
  
  return data.map((item, index) => {
    const percentage = ((item.count || 0) / total) * 100;
    const angle = (item.count / total) * 360;
    
    const startAngle = currentAngle * Math.PI / 180;
    const endAngle = (currentAngle + angle) * Math.PI / 180;
    
    const x1 = cx + radius * Math.cos(startAngle);
    const y1 = cy + radius * Math.sin(startAngle);
    const x2 = cx + radius * Math.cos(endAngle);
    const y2 = cy + radius * Math.sin(endAngle);
    
    const largeArc = angle > 180 ? 1 : 0;
    
    const path = [
      `M ${cx} ${cy}`,
      `L ${x1} ${y1}`,
      `A ${radius} ${radius} 0 ${largeArc} 1 ${x2} ${y2}`,
      'Z'
    ].join(' ');
    
    currentAngle += angle;
    
    return {
      path,
      color: getPieColor(index),
      label: item.type,
      value: item.count,
      percentage: percentage.toFixed(1)
    };
  });
};

// 解决率折线图：计算点坐标
const getResolutionLinePoints = (data) => {
  if (!data || data.length === 0) return '60,210 560,210';
  
  const points = data.map((item, index) => {
    const x = 60 + (index * (500 / Math.max(1, data.length - 1)));
    const y = 210 - ((item.rate || 0) / 100) * 200; // 0-100% 映射到 210-10
    return `${x},${y}`;
  });
  
  return points.join(' ');
};

// 解决率折线图：计算填充区域
const getResolutionArea = (data) => {
  if (!data || data.length === 0) return '60,210 560,210';
  
  const points = getResolutionLinePoints(data);
  const lastX = 60 + ((data.length - 1) * (500 / Math.max(1, data.length - 1)));
  return `60,210 ${points} ${lastX},210`;
};

// 解决率折线图：获取数据点信息
const getResolutionDataPoints = (data) => {
  if (!data || data.length === 0) return [];
  
  return data.map((item, index) => ({
    x: 60 + (index * (500 / Math.max(1, data.length - 1))),
    y: 210 - ((item.rate || 0) / 100) * 200,
    value: item.rate || 0,
    label: item.date
  }));
};

// 渲染 Markdown（使用与客户端相同的方式）
const renderMarkdown = (content) => {
  try {
    if (!content) return '';
    return marked.parse(content);
  } catch (error) {
    console.error('Markdown渲染失败:', error);
    return content.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>');
  }
};

// 监听页面切换，加载对应数据
const handlePageChange = (page) => {
  currentPage.value = page;
  
  if (page === 'users' && users.value.length === 0) {
    loadUsers();
  } else if (page === 'chat-history' && chatHistory.value.length === 0) {
    loadChatHistory();
  } else if (page === 'analytics') {
    loadAnalyticsData(); // 数据分析页面每次都重新加载以获取最新数据
  }
};
</script>

<style scoped>
.admin-dashboard {
  display: flex;
  height: 100vh;
  overflow: hidden;
  background: linear-gradient(135deg, #0f172a 0%, #1e293b 50%, #334155 100%);
  color: #e2e8f0;
}

/* 侧边栏 */
.sidebar {
  width: 280px;
  height: 100vh;
  background: rgba(15, 23, 42, 0.95);
  backdrop-filter: blur(20px);
  color: white;
  display: flex;
  flex-direction: column;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
  border-right: 1px solid rgba(59, 130, 246, 0.2);
  position: fixed;
  left: 0;
  top: 0;
  overflow-y: hidden;
}

.sidebar-header {
  padding: 2rem;
  border-bottom: 1px solid rgba(59, 130, 246, 0.2);
  margin-bottom: 1rem;
}

.logo {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  font-size: 1.5rem;
  font-weight: 700;
  color: #60a5fa;
  text-shadow: 0 0 10px rgba(96, 165, 250, 0.3);
}

.logo svg {
  width: 28px;
  height: 28px;
  color: #3b82f6;
  filter: drop-shadow(0 0 8px rgba(59, 130, 246, 0.4));
}

.sidebar-nav {
  flex: 1;
  padding: 1rem 0;
  overflow-y: auto;
  overflow-x: hidden;
}

.sidebar-nav::-webkit-scrollbar {
  width: 6px;
}

.sidebar-nav::-webkit-scrollbar-track {
  background: rgba(15, 23, 42, 0.3);
}

.sidebar-nav::-webkit-scrollbar-thumb {
  background: rgba(59, 130, 246, 0.5);
  border-radius: 3px;
}

.sidebar-nav::-webkit-scrollbar-thumb:hover {
  background: rgba(59, 130, 246, 0.7);
}

.nav-list {
  list-style: none;
  margin: 0;
  padding: 0;
}

.nav-item {
  margin: 0.25rem 0;
}

.nav-link {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  width: 100%;
  padding: 0.875rem 2rem;
  background: none;
  border: none;
  color: #94a3b8;
  font-size: 0.875rem;
  font-weight: 500;
  text-align: left;
  cursor: pointer;
  transition: all 0.3s ease;
  border-left: 3px solid transparent;
  position: relative;
}

.nav-link:hover {
  background: rgba(59, 130, 246, 0.1);
  color: #60a5fa;
  transform: translateX(4px);
  box-shadow: 0 0 20px rgba(59, 130, 246, 0.1);
}

.nav-item.active .nav-link {
  background: rgba(59, 130, 246, 0.15);
  color: #60a5fa;
  border-left-color: #3b82f6;
  box-shadow: 0 0 20px rgba(59, 130, 246, 0.2);
}

.nav-icon {
  width: 20px;
  height: 20px;
  filter: drop-shadow(0 0 4px rgba(96, 165, 250, 0.3));
}

.sidebar-footer {
  padding: 2rem;
  border-top: 1px solid rgba(59, 130, 246, 0.2);
  flex-shrink: 0;
}

.logout-btn {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  width: 100%;
  padding: 0.875rem 1rem;
  background: rgba(239, 68, 68, 0.1);
  border: 1px solid rgba(239, 68, 68, 0.3);
  color: #fca5a5;
  font-size: 0.875rem;
  font-weight: 500;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.logout-btn:hover {
  background: rgba(239, 68, 68, 0.2);
  color: #f87171;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.2);
}

.logout-icon {
  width: 18px;
  height: 18px;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: rgba(15, 23, 42, 0.3);
  margin-left: 280px;
  height: 100vh;
  overflow: hidden;
}

.top-header {
  background: rgba(30, 41, 59, 0.8);
  backdrop-filter: blur(20px);
  padding: 1.5rem 2rem;
  border-bottom: 1px solid rgba(59, 130, 246, 0.2);
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}

.page-title {
  font-size: 1.75rem;
  font-weight: 700;
  color: #f1f5f9;
  margin: 0;
  text-shadow: 0 0 20px rgba(241, 245, 249, 0.3);
}

.header-right {
  display: flex;
  align-items: center;
}

.admin-info {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.admin-name {
  font-weight: 500;
  color: #94a3b8;
}

.admin-avatar {
  width: 36px;
  height: 36px;
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 0.875rem;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.page-content {
  flex: 1;
  padding: 2rem;
  overflow-y: auto;
  overflow-x: hidden;
}

.page-content::-webkit-scrollbar {
  width: 8px;
}

.page-content::-webkit-scrollbar-track {
  background: rgba(15, 23, 42, 0.3);
}

.page-content::-webkit-scrollbar-thumb {
  background: rgba(59, 130, 246, 0.5);
  border-radius: 4px;
}

.page-content::-webkit-scrollbar-thumb:hover {
  background: rgba(59, 130, 246, 0.7);
}

/* 页面通用样式 */
.page-header {
  margin-bottom: 2rem;
}

.page-header h2 {
  font-size: 1.75rem;
  font-weight: 700;
  color: #f1f5f9;
  margin: 0 0 0.5rem 0;
  text-shadow: 0 0 20px rgba(241, 245, 249, 0.3);
}

.page-header p {
  color: #94a3b8;
  margin: 0;
  font-size: 1rem;
}

/* 文件上传页面 */
.upload-section {
  background: rgba(30, 41, 59, 0.8);
  backdrop-filter: blur(20px);
  padding: 2rem;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  margin-bottom: 2rem;
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.upload-history h3 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #f1f5f9;
  margin-bottom: 1.5rem;
  text-shadow: 0 0 10px rgba(241, 245, 249, 0.3);
}

.history-list {
  background: rgba(15, 23, 42, 0.5);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
  overflow: hidden;
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.25rem 1.5rem;
  border-bottom: 1px solid rgba(59, 130, 246, 0.1);
  transition: all 0.3s ease;
}

.history-item:hover {
  background: rgba(59, 130, 246, 0.05);
  transform: translateX(4px);
}

.history-item:last-child {
  border-bottom: none;
}

.file-info {
  flex: 1;
}

.file-name {
  font-weight: 600;
  color: #f1f5f9;
  margin-bottom: 0.25rem;
}

.file-meta {
  font-size: 0.875rem;
  color: #94a3b8;
}

.file-status {
  padding: 0.25rem 0.75rem;
  border-radius: 6px;
  font-size: 0.75rem;
  font-weight: 600;
}

.file-status.success {
  background: rgba(34, 197, 94, 0.2);
  color: #4ade80;
  border: 1px solid rgba(34, 197, 94, 0.3);
}

/* 用户管理页面 */
.user-stats {
  display: flex;
  gap: 1.5rem;
  margin-bottom: 2rem;
  padding: 1.5rem;
  background: rgba(30, 41, 59, 0.8);
  backdrop-filter: blur(20px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.25rem;
}

.stat-label {
  font-size: 0.875rem;
  color: #94a3b8;
  font-weight: 500;
}

.stat-value {
  font-size: 1.75rem;
  font-weight: 700;
  color: #60a5fa;
  text-shadow: 0 0 10px rgba(96, 165, 250, 0.3);
}

.loading-state {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  padding: 2rem;
  color: #94a3b8;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid rgba(59, 130, 246, 0.3);
  border-radius: 50%;
  border-top-color: #3b82f6;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.empty-state {
  text-align: center;
  padding: 2rem;
  color: #94a3b8;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  margin-top: 1.5rem;
  padding: 1.5rem;
  background: rgba(30, 41, 59, 0.8);
  backdrop-filter: blur(20px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.page-btn {
  padding: 0.75rem 1.5rem;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.page-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(59, 130, 246, 0.4);
}

.page-btn:disabled {
  background: rgba(59, 130, 246, 0.3);
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.page-info {
  color: #94a3b8;
  font-weight: 500;
}

.edit-btn {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 6px;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
  display: inline-block;
  margin-right: 0.75rem;
  vertical-align: top;
}

.edit-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
}

.delete-btn {
  background: linear-gradient(135deg, #c86565 0%, #8e1e1e 100%);
  color: white;
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 6px;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(239, 68, 68, 0.3);
  display: inline-block;
  vertical-align: top;
}

.delete-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
}

.users-table {
  background: rgba(30, 41, 59, 0.8);
  backdrop-filter: blur(20px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  overflow: hidden;
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.table-header {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 0.5fr 0.5fr;
  background: rgba(59, 130, 246, 0.1);
  padding: 1.25rem 1.5rem;
  font-weight: 600;
  color: #e2e8f0;
  border-bottom: 1px solid rgba(59, 130, 246, 0.2);
}

.table-body {
  display: flex;
  flex-direction: column;
}

.table-row {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 0.5fr 0.5fr;
  padding: 1.25rem 1.5rem;
  border-bottom: 1px solid rgba(59, 130, 246, 0.1);
  align-items: center;
  transition: all 0.3s ease;
  color: #e2e8f0;
}

.table-row:hover {
  background: rgba(59, 130, 246, 0.05);
  transform: translateX(2px);
}

.table-row:last-child {
  border-bottom: none;
}

.table-cell {
  color: #e2e8f0;
}

.status-badge {
  padding: 0.25rem 0.75rem;
  border-radius: 6px;
  font-size: 0.75rem;
  font-weight: 600;
}

.status-badge.active {
  background: rgba(34, 197, 94, 0.2);
  color: #4ade80;
  border: 1px solid rgba(34, 197, 94, 0.3);
}

.status-badge.inactive {
  background: rgba(239, 68, 68, 0.2);
  color: #f87171;
  border: 1px solid rgba(239, 68, 68, 0.3);
}

.action-btn {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
  display: inline-block;
  margin-right: 0.5rem;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
}

.action-btn:last-child {
  margin-right: 0;
}

/* 对话历史页面 */
.history-filters {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
  padding: 1.5rem;
  background: rgba(30, 41, 59, 0.8);
  backdrop-filter: blur(20px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.filter-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  position: relative;
}

.filter-group:last-child {
  flex-direction: row;
  align-items: flex-end;
  gap: 0.75rem;
}

.filter-group label {
  font-weight: 500;
  color: #e2e8f0;
  font-size: 0.875rem;
  margin-bottom: 0.25rem;
}

.filter-select, .filter-input {
  padding: 0.75rem 1rem;
  border: 1px solid rgba(59, 130, 246, 0.3);
  border-radius: 8px;
  background: rgba(15, 23, 42, 0.5);
  color: #e2e8f0;
  font-size: 0.875rem;
  transition: all 0.3s ease;
}

.filter-select:focus, .filter-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
  background: rgba(15, 23, 42, 0.8);
}

.filter-input::placeholder {
  color: #64748b;
  opacity: 0.7;
}

.filter-apply-btn, .filter-reset-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 8px;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.filter-apply-btn {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
}

.filter-apply-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
}

.filter-reset-btn {
  background: rgba(100, 116, 139, 0.2);
  color: #94a3b8;
  border: 1px solid rgba(100, 116, 139, 0.3);
}

.filter-reset-btn:hover {
  background: rgba(100, 116, 139, 0.3);
  color: #cbd5e1;
  transform: translateY(-1px);
}

.filter-icon {
  width: 16px;
  height: 16px;
}

.filter-status {
  margin-bottom: 1.5rem;
  padding: 1rem 1.5rem;
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.1), rgba(59, 130, 246, 0.05));
  border: 1px solid rgba(59, 130, 246, 0.3);
  border-radius: 12px;
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.status-item {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  color: #e2e8f0;
  font-size: 0.875rem;
}

.status-icon {
  width: 18px;
  height: 18px;
  color: #60a5fa;
  flex-shrink: 0;
}

.status-item strong {
  color: #60a5fa;
  font-weight: 600;
}

.chat-history-list {
  background: rgba(30, 41, 59, 0.8);
  backdrop-filter: blur(20px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  overflow: visible;
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.history-item {
  padding: 1.5rem;
  border-bottom: 1px solid rgba(59, 130, 246, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
}

.history-item:hover {
  background: rgba(59, 130, 246, 0.05);
}

.history-item.expanded {
  background: rgba(59, 130, 246, 0.08);
  border-left: 3px solid #3b82f6;
  padding-left: 1.5rem;
}

.history-item:last-child {
  border-bottom: none;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  flex-wrap: wrap;
}

.username {
  font-weight: 600;
  color: #f1f5f9;
  font-size: 1rem;
}

.session-id {
  font-size: 0.875rem;
  color: #94a3b8;
  background: rgba(15, 23, 42, 0.5);
  padding: 0.25rem 0.75rem;
  border-radius: 6px;
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.message-count {
  font-size: 0.75rem;
  color: #60a5fa;
  background: rgba(59, 130, 246, 0.15);
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-weight: 500;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.timestamp {
  font-size: 0.875rem;
  color: #94a3b8;
}

.expand-icon {
  font-size: 0.875rem;
  color: #60a5fa;
  font-weight: bold;
  transition: transform 0.3s ease;
}

.history-item.expanded .expand-icon {
  transform: rotate(0deg);
}

.history-content {
  margin-top: 0.75rem;
}

/* 预览样式 */
.history-preview {
  margin-top: 1rem;
  padding: 1rem;
  background: rgba(15, 23, 42, 0.3);
  border-radius: 8px;
  border-left: 3px solid rgba(59, 130, 246, 0.3);
}

.preview-text {
  color: #cbd5e1;
  font-size: 0.875rem;
  line-height: 1.6;
  margin-bottom: 0.5rem;
}

.preview-hint {
  font-size: 0.75rem;
  color: #60a5fa;
  font-style: italic;
  opacity: 0.8;
}

/* 详情样式 */
.history-details {
  margin-top: 1rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  max-height: none;
  overflow: visible;
}

.message-item {
  display: flex;
  gap: 1rem;
  padding: 1rem;
  border-radius: 8px;
  transition: all 0.3s ease;
  overflow: hidden;
  min-height: auto;
  width: 100%;
  box-sizing: border-box;
}

.message-item.user {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.15), rgba(59, 130, 246, 0.08));
  border-left: 3px solid #3b82f6;
}

.message-item.ai {
  background: linear-gradient(135deg, rgba(34, 197, 94, 0.15), rgba(34, 197, 94, 0.08));
  border-left: 3px solid #22c55e;
}

.message-item:hover {
  transform: translateX(4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.message-label {
  font-weight: 600;
  font-size: 0.875rem;
  min-width: 50px;
  flex-shrink: 0;
}

.message-item.user .message-label {
  color: #60a5fa;
}

.message-item.ai .message-label {
  color: #4ade80;
}

.message-content {
  flex: 1;
  color: #e2e8f0;
  font-size: 0.875rem;
  line-height: 1.8;
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow-wrap: break-word;
  overflow-x: auto;
  margin: 0;
  padding: 0;
  font-family: inherit;
  background: none;
  min-width: 0;
  max-width: 100%;
}

/* Markdown 渲染样式 */
.markdown-content {
  white-space: normal;
}

.markdown-content :deep(h1),
.markdown-content :deep(h2),
.markdown-content :deep(h3),
.markdown-content :deep(h4),
.markdown-content :deep(h5),
.markdown-content :deep(h6) {
  color: #60a5fa !important;
  margin: 1rem 0 0.5rem 0 !important;
  font-weight: 600 !important;
  line-height: 1.4 !important;
}

.markdown-content :deep(h1) { font-size: 1.5rem !important; }
.markdown-content :deep(h2) { font-size: 1.3rem !important; }
.markdown-content :deep(h3) { font-size: 1.1rem !important; }
.markdown-content :deep(h4) { font-size: 1rem !important; }

.markdown-content :deep(p) {
  margin: 0.5rem 0 !important;
  line-height: 1.8 !important;
}

.markdown-content :deep(code) {
  background: rgba(15, 23, 42, 0.6) !important;
  padding: 0.2rem 0.4rem !important;
  border-radius: 4px !important;
  font-family: 'Consolas', 'Monaco', monospace !important;
  font-size: 0.85em !important;
  color: #fbbf24 !important;
}

.markdown-content :deep(pre) {
  background: rgba(15, 23, 42, 0.8) !important;
  padding: 1rem !important;
  border-radius: 8px !important;
  overflow-x: auto !important;
  margin: 1rem 0 !important;
  border-left: 3px solid #3b82f6 !important;
  white-space: pre !important;
  line-height: 1.6 !important;
  max-width: 100% !important;
}

.markdown-content :deep(pre code) {
  background: none !important;
  padding: 0 !important;
  color: #e2e8f0 !important;
  font-size: 0.875rem !important;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace !important;
  white-space: pre !important;
  display: block !important;
}

.markdown-content :deep(pre code.hljs) {
  background: transparent !important;
}

.markdown-content :deep(ul),
.markdown-content :deep(ol) {
  margin: 0.5rem 0 !important;
  padding-left: 2rem !important;
}

.markdown-content :deep(li) {
  margin: 0.25rem 0 !important;
  line-height: 1.6 !important;
}

.markdown-content :deep(blockquote) {
  border-left: 3px solid #3b82f6 !important;
  padding-left: 1rem !important;
  margin: 1rem 0 !important;
  color: #94a3b8 !important;
  font-style: italic !important;
}

.markdown-content :deep(a) {
  color: #60a5fa !important;
  text-decoration: underline !important;
}

.markdown-content :deep(a:hover) {
  color: #93c5fd !important;
}

.markdown-content :deep(table) {
  border-collapse: collapse !important;
  width: 100% !important;
  margin: 1rem 0 !important;
}

.markdown-content :deep(th),
.markdown-content :deep(td) {
  border: 1px solid rgba(59, 130, 246, 0.3) !important;
  padding: 0.5rem !important;
  text-align: left !important;
}

.markdown-content :deep(th) {
  background: rgba(59, 130, 246, 0.2) !important;
  font-weight: 600 !important;
}

.markdown-content :deep(strong) {
  color: #fbbf24 !important;
  font-weight: 600 !important;
}

.markdown-content :deep(em) {
  color: #a78bfa !important;
  font-style: italic !important;
}

.markdown-content :deep(hr) {
  border: none !important;
  border-top: 1px solid rgba(59, 130, 246, 0.3) !important;
  margin: 1.5rem 0 !important;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 4rem 2rem;
  color: #94a3b8;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
  opacity: 0.5;
}

/* 数据分析页面 */
.analytics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 2rem;
}

.analytics-card {
  background: rgba(30, 41, 59, 0.8);
  backdrop-filter: blur(20px);
  padding: 2rem;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(59, 130, 246, 0.2);
  transition: all 0.3s ease;
}

.analytics-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.4);
  border-color: rgba(59, 130, 246, 0.4);
}

.analytics-card h3 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #f1f5f9;
  margin-bottom: 1.5rem;
  text-shadow: 0 0 10px rgba(241, 245, 249, 0.3);
}

.analytics-placeholder {
  height: 200px;
  background: rgba(15, 23, 42, 0.5);
  border: 2px dashed rgba(59, 130, 246, 0.3);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #94a3b8;
  font-size: 1rem;
  margin-top: 1rem;
}

.analytics-placeholder:hover {
  border-color: rgba(59, 130, 246, 0.5);
  color: #60a5fa;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    width: 200px;
  }
  
  .page-content {
    padding: 1rem;
  }
  
  .table-header,
  .table-row {
    grid-template-columns: 1fr;
    gap: 0.5rem;
  }
  
  .history-filters {
    flex-direction: column;
    gap: 1rem;
  }
  
  .analytics-grid {
    grid-template-columns: 1fr;
  }
  
  .user-stats {
    flex-direction: column;
    gap: 1rem;
  }
  
  .filter-group {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
}

@media (max-width: 640px) {
  .admin-dashboard {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    height: auto;
  }
  
  .sidebar-nav {
    display: flex;
    overflow-x: auto;
  }
  
  .nav-list {
    display: flex;
    gap: 0.5rem;
  }
  
  .nav-item {
    margin: 0;
  }
  
  .nav-link {
    white-space: nowrap;
    padding: 0.5rem 1rem;
  }
}

/* ==================== 数据分析页面样式 ==================== */

.analytics-page {
  padding: 0;
}

/* 统计卡片概览 */
.stats-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.stat-box {
  background: linear-gradient(135deg, rgba(30, 41, 59, 0.9) 0%, rgba(51, 65, 85, 0.9) 100%);
  border: 1px solid rgba(148, 163, 184, 0.2);
  border-radius: 12px;
  padding: 1.5rem;
  display: flex;
  align-items: center;
  gap: 1.5rem;
  transition: all 0.3s ease;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.stat-box:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 15px rgba(59, 130, 246, 0.3);
  border-color: rgba(59, 130, 246, 0.5);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.stat-icon svg {
  width: 30px;
  height: 30px;
}

.users-stat {
  background: linear-gradient(135deg, #3b82f6, #2563eb);
}

.conversations-stat {
  background: linear-gradient(135deg, #10b981, #059669);
}

.active-stat {
  background: linear-gradient(135deg, #f59e0b, #d97706);
}

.messages-stat {
  background: linear-gradient(135deg, #8b5cf6, #7c3aed);
}

.stat-details {
  flex: 1;
}

.stat-value {
  font-size: 2rem;
  font-weight: 700;
  color: #f1f5f9;
  margin-bottom: 0.25rem;
  line-height: 1;
}

.stat-label {
  font-size: 0.875rem;
  color: #94a3b8;
  font-weight: 500;
}

/* 图表标题图标 */
.chart-title-icon {
  width: 20px;
  height: 20px;
  color: #3b82f6;
  flex-shrink: 0;
}

/* 排行榜 */
.ranking-section {
  background: linear-gradient(135deg, rgba(30, 41, 59, 0.9) 0%, rgba(51, 65, 85, 0.9) 100%);
  border: 1px solid rgba(148, 163, 184, 0.2);
  border-radius: 12px;
  padding: 1.5rem;
  margin-bottom: 2rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.ranking-section h3 {
  font-size: 1.125rem;
  color: #f1f5f9;
  margin: 0 0 1.5rem 0;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.ranking-list {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.ranking-item {
  display: grid;
  grid-template-columns: 50px 1fr auto 200px;
  gap: 1rem;
  align-items: center;
  background: rgba(15, 23, 42, 0.5);
  padding: 1rem;
  border-radius: 8px;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.ranking-item:hover {
  background: rgba(59, 130, 246, 0.1);
  border-color: rgba(59, 130, 246, 0.3);
  transform: translateX(5px);
}

.ranking-item.top-three {
  background: linear-gradient(90deg, rgba(251, 191, 36, 0.1), rgba(15, 23, 42, 0.5));
  border-left: 3px solid #fbbf24;
}

.rank-badge {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  font-size: 1.125rem;
  background: linear-gradient(135deg, #334155, #1e293b);
  color: #cbd5e1;
  border: 2px solid rgba(148, 163, 184, 0.3);
}

.rank-badge.rank-1 {
  background: linear-gradient(135deg, #fbbf24, #f59e0b);
  color: #1e293b;
  border-color: #fbbf24;
  box-shadow: 0 0 15px rgba(251, 191, 36, 0.5);
}

.rank-badge.rank-2 {
  background: linear-gradient(135deg, #94a3b8, #64748b);
  color: #1e293b;
  border-color: #94a3b8;
  box-shadow: 0 0 10px rgba(148, 163, 184, 0.5);
}

.rank-badge.rank-3 {
  background: linear-gradient(135deg, #d97706, #b45309);
  color: #fff;
  border-color: #d97706;
  box-shadow: 0 0 10px rgba(217, 119, 6, 0.5);
}

.rank-user {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: linear-gradient(135deg, #3b82f6, #2563eb);
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  color: #fff;
  font-size: 0.875rem;
}

.user-name {
  font-weight: 600;
  color: #e2e8f0;
  font-size: 0.938rem;
}

.rank-count {
  display: flex;
  align-items: baseline;
  gap: 0.5rem;
}

.count-number {
  font-size: 1.5rem;
  font-weight: 700;
  color: #3b82f6;
}

.count-label {
  font-size: 0.875rem;
  color: #94a3b8;
}

.rank-bar {
  position: relative;
  height: 8px;
  background: rgba(15, 23, 42, 0.8);
  border-radius: 4px;
  overflow: hidden;
}

.rank-bar-fill {
  height: 100%;
  background: linear-gradient(90deg, #3b82f6, #2563eb);
  border-radius: 4px;
  transition: width 0.6s ease;
  box-shadow: 0 0 8px rgba(59, 130, 246, 0.6);
}

/* 平均统计 */
.avg-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1.5rem;
}

.avg-stat-item {
  background: linear-gradient(135deg, rgba(30, 41, 59, 0.9) 0%, rgba(51, 65, 85, 0.9) 100%);
  border: 1px solid rgba(148, 163, 184, 0.2);
  border-radius: 12px;
  padding: 1.5rem;
  display: flex;
  align-items: center;
  gap: 1.5rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.avg-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #06b6d4, #0891b2);
  flex-shrink: 0;
}

.avg-icon svg {
  width: 30px;
  height: 30px;
  color: #fff;
}

.avg-content {
  flex: 1;
}

.avg-value {
  font-size: 2rem;
  font-weight: 700;
  color: #06b6d4;
  margin-bottom: 0.25rem;
  line-height: 1;
}

.avg-label {
  font-size: 0.875rem;
  color: #94a3b8;
  font-weight: 500;
}

/* 响应式 */
@media (max-width: 768px) {
  .stats-overview {
    grid-template-columns: 1fr;
  }
  
  .ranking-item {
    grid-template-columns: 40px 1fr;
    grid-template-rows: auto auto;
  }
  
  .rank-count,
  .rank-bar {
    grid-column: 2;
  }
}

/* ==================== 高级图表样式 ==================== */

.advanced-charts {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  margin-top: 2rem;
}

.advanced-charts .full-width {
  width: 100%;
}

.chart-card,
.line-chart-card,
.pie-chart-card,
.resolution-chart-card {
  background: linear-gradient(135deg, rgba(30, 41, 59, 0.9) 0%, rgba(51, 65, 85, 0.9) 100%);
  border: 1px solid rgba(148, 163, 184, 0.2);
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.chart-card h3,
.line-chart-card h3,
.pie-chart-card h3,
.resolution-chart-card h3 {
  font-size: 1.125rem;
  color: #f1f5f9;
  margin: 0 0 1.5rem 0;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.chart-card:hover,
.line-chart-card:hover,
.pie-chart-card:hover,
.resolution-chart-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 15px rgba(59, 130, 246, 0.2);
}

/* 折线图容器 */
.line-chart-container,
.resolution-chart-container {
  width: 100%;
  height: 300px;
  background: rgba(15, 23, 42, 0.5);
  border-radius: 8px;
  padding: 1rem;
  overflow: hidden;
}

.line-chart-svg,
.resolution-chart-svg {
  width: 100%;
  height: 100%;
}

.data-point {
  cursor: pointer;
  transition: all 0.3s ease;
}

.data-point:hover {
  r: 7;
  filter: drop-shadow(0 0 8px rgba(59, 130, 246, 0.8));
}

/* 饼图容器 */
.pie-chart-container {
  display: flex;
  align-items: flex-start;
  justify-content: center;
  gap: 3rem;
  background: rgba(15, 23, 42, 0.5);
  border-radius: 8px;
  padding: 2rem;
  min-height: 350px;
}

.pie-chart-wrapper {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pie-chart-svg {
  width: 300px;
  height: 300px;
}

.pie-slice {
  cursor: pointer;
  transition: all 0.3s ease;
}

.pie-path {
  transition: all 0.3s ease;
  filter: drop-shadow(0 4px 6px rgba(0, 0, 0, 0.3));
}

.pie-slice:hover .pie-path {
  filter: drop-shadow(0 6px 12px rgba(0, 0, 0, 0.5));
}

/* 饼图图例 */
.pie-legend {
  flex: 0 0 auto;
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  justify-content: center;
  min-width: 250px;
  max-width: 300px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 0.875rem;
  padding: 0.75rem 1rem;
  background: rgba(15, 23, 42, 0.5);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
  min-width: 0;
}

.legend-item:hover {
  background: rgba(59, 130, 246, 0.1);
  border-color: rgba(59, 130, 246, 0.3);
  transform: translateX(5px);
}

.legend-color {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  flex-shrink: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.legend-label {
  flex: 1;
  font-weight: 600;
  color: #e2e8f0;
  font-size: 0.9rem;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
}

.legend-value {
  font-weight: 700;
  color: #3b82f6;
  font-size: 0.95rem;
  flex-shrink: 0;
  margin-left: auto;
}

/* SVG文本样式 */
svg text {
  user-select: none;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .advanced-charts {
    grid-template-columns: 1fr;
  }
  
  .pie-chart-container {
    flex-direction: column;
    align-items: center;
  }
  
  .pie-chart-wrapper {
    width: 100%;
    max-width: 350px;
  }
  
  .pie-chart-svg {
    width: 100%;
    height: auto;
  }
  
  .pie-legend {
    width: 100%;
    max-width: 400px;
  }
}

@media (max-width: 768px) {
  .line-chart-container,
  .resolution-chart-container {
    height: 250px;
  }
  
  .advanced-charts {
    grid-template-columns: 1fr;
  }
}
</style>
